// pages/transaction/buy/buy.js
import api from '../../../api/api.js'
import Notify from '../../../miniprogram_npm/vant-weapp/notify/notify.js'
import {formatProductType} from '../../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    financeProductId:null,
    loading: true,
    loading2: true,
    financeProduct: {},
    profitInfo: {},
    buyPrice:null,
    buyUnit:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (query) {
    this.setData({
      financeProductId:query.productId
    });
    this.getFinanceProduct(query.productId);
    this.getUserProfit();
  },
  onChange(event) {
    const {key} = event.currentTarget.dataset;
    this.setData({
      [key]: event.detail,
    });
  },
  addUnit(e){
    this.getFinanceProduct(e.target.dataset.productId);
  },
  changePrice(e){
    this.setData({
      buyPrice: e.detail
    })
  },
  changeCount(e){
    this.setData({
      buyUnit: e.detail
    })
  },
  buyUserProduct(){
    if(!this.data.buyPrice){
      Notify('请输入价格');
    }else if(!this.data.buyUnit){
      Notify('请输入数量');
    }else{
      api.buyUserProduct({
        financeProductId:Number(this.data.financeProductId),
        buyPrice:this.data.buyPrice,
        buyUnit:this.data.buyUnit,
      }).then(res=>{
        if(res.code==='0'){
          Notify({
            text:'买入成功',
            backgroundColor:'#4b0'
          });
          this.setData({
            buyPrice:null,
            buyUnit:null,
          });
          this.getUserProfit();
        }
      })
    }
  },
  toSelect(){
    wx.navigateTo({
      url: '/pages/transaction/select/select'
    })
  },

  getFinanceProduct(id) {
    this.setData({
      loading: true
    });
    api.getFinanceProduct({
      financeProductId: id
    }).then(res => {
      let _data = res.data.financeProduct;
      _data.showProductType=formatProductType(_data.productType);
      this.setData({
        loading: false,
        financeProduct:_data,
        buyPrice:_data.nowPrice
      });
    })
  },
  getUserProfit() {
    api.getUserProfit().then(res => {
      let _data = res.data.data;
      _data.userProductList = _data.userProductList.map(item => {
        item.showProductType = formatProductType(item.productType);
        return item;
      });
      this.setData({
        profitInfo: _data,
        loading2: false
      });
    });
  },
});